#!/usr/bin/env python
# encoding: utf-8

import os
import re
import copy
import json
from collections import OrderedDict

from common.libs.Log import logger

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

from ui.device import Ui_Form
from ui import images

from .DeviceSmartWidget import DeviceSmartWidget 
from .DeviceManageWidget import DeviceManageWidget
from .DeviceService import DeviceServiceJson

from .mqtt.MqttSetDialog import MqttSetDialog 
from .mqtt.MqttThread import MqttThread

import PyQt5_stylesheets
import qtawesome as qta

CONFIG_DEVICE_CMD = os.getcwd()+'/conf/device_cmd.json'

class DeviceItemGroupBox(QGroupBox):
    def __init__(self, parent = None, conf = ""):
        super(QGroupBox, self).__init__(parent)
        self.setTitle(conf['model'])
        if conf['model'] == 'FSC-01': # 光机
            pass
        if conf['model'] == "FSC-02": # 门禁
            self.menInit(conf)
        if conf['model'] == "FSC-03": # 红外
            self.hongwaiInit(conf)
        if conf['model'] == "FSC-04": # 辐射源
            self.fusheyuanInit(conf)
        if conf['model'] == "FSC-05": # 轨道
            self.guidaoInit(conf)

    def fusheyuanInit(self, conf):
        # 设备图片
        self.label_image = QLabel(self, pixmap=QPixmap(':icons/images/hongwai.png'))
        pixmap = QPixmap(':icons/images/fusheyuan-big.png')
        pixmap.scaled(self.label_image.size(), Qt.KeepAspectRatio)
        self.label_image.setScaledContents(True)
        self.label_image.setPixmap(pixmap)

        self.label_sn = QLabel("编号: %s" % conf['sn'])
        self.label_name = QLabel("名称: %s" % conf['name'])
        self.label_position = QLabel("位置: %s" % conf['position'])
        self.label_model= QLabel("型号: %s" % conf['model'])

        self.vlayout_info = QVBoxLayout()
        self.vlayout_info.addWidget(self.label_name)
        self.vlayout_info.addWidget(self.label_position)
        self.vlayout_info.addWidget(self.label_model)
        self.vlayout_info.addWidget(self.label_sn)

        # 设备状态 -> 在线状态
        self.online_button = None
        self.online_button = QPushButton('离线')
        self.online_button.setIcon(QIcon(':icons/images/circle-red'))
        self.online_button.setStyleSheet("background-color: rgb(255, 255, 255);")
        self.online_button.setStyleSheet("border:none")
        self.online_button.setFlat(True)

        self.open_status_button = QPushButton('关闭')
        self.open_status_button.setIcon(QIcon(':icons/images/fusheyuan-green'))
        self.open_status_button.setStyleSheet("background-color: rgb(255, 255, 255);")
        self.open_status_button.setStyleSheet("border:none")
        self.open_status_button.setFlat(True)

        self.open_button = QPushButton('开启')
        self.close_button = QPushButton('关闭')

        self.gridLayout = QGridLayout()
        self.gridLayout.addWidget(self.label_image, 0,0,1,1)
        self.gridLayout.addLayout(self.vlayout_info, 0,1,1,1)
        self.gridLayout.addWidget(self.online_button, 1,0,1,1)
        self.gridLayout.addWidget(self.open_status_button, 2,0,1,1)
        self.gridLayout.addWidget(self.open_button, 1,1,1,1)
        self.gridLayout.addWidget(self.close_button, 2,1,1,1)

        self.setLayout(self.gridLayout)

    def hongwaiInit(self, conf):
        # 设备图片
        self.label_image = QLabel(self, pixmap=QPixmap(':icons/images/hongwai.png'))
        pixmap = QPixmap(':icons/images/hongwai-big.png')
        # pixmap.scaled(self.label_image.size(), Qt.KeepAspectRatio)
        # self.label_image.setScaledContents(True)
        self.label_image.setPixmap(pixmap)

        self.label_sn = QLabel("编号: %s" % conf['sn'])
        self.label_name = QLabel("名称: %s" % conf['name'])
        self.label_position = QLabel("位置: %s" % conf['position'])
        self.label_model= QLabel("型号: %s" % conf['model'])

        self.vlayout_info = QVBoxLayout()
        self.vlayout_info.addWidget(self.label_name)
        self.vlayout_info.addWidget(self.label_position)
        self.vlayout_info.addWidget(self.label_model)
        self.vlayout_info.addWidget(self.label_sn)

        # 设备状态 -> 在线状态
        self.online_button = None
        self.online_button = QPushButton('离线')
        self.online_button.setIcon(QIcon(':icons/images/circle-red'))
        self.online_button.setStyleSheet("background-color: rgb(255, 255, 255);")
        self.online_button.setStyleSheet("border:none")
        self.online_button.setFlat(True)

        self.people_button = QPushButton('无人')
        self.people_button.setIcon(QIcon(':icons/images/people-red'))
        # self.people_button.setIcon(qta.icon('fa5s.user', color='springgreen'))
        self.people_button.setStyleSheet("background-color: rgb(255, 255, 255);")
        self.people_button.setStyleSheet("border:none")
        self.people_button.setFlat(True)

        self.vlayout_status = QVBoxLayout()
        self.vlayout_status.addWidget(self.online_button)
        self.vlayout_status.addWidget(self.people_button)

        self.gridLayout = QGridLayout()
        self.gridLayout.addWidget(self.label_image, 0,0,1,1)
        self.gridLayout.addLayout(self.vlayout_info, 0,1,1,1)
        self.gridLayout.addLayout(self.vlayout_status, 0,2,1,1)
        # self.gridLayout.addWidget(self.online_button, 1,0,1,1)
        # self.gridLayout.addWidget(self.people_button, 2,0,1,1)

        self.setLayout(self.gridLayout)
        # self.setMaximumSize(QSize(200, 200))

    def menInit(self, conf):
        # self.setMaximumSize(QSize(200, 200))
        # 设备图片
        self.label_image = QLabel(self, pixmap=QPixmap(':icons/images/men.png'))
        pixmap = QPixmap(':icons/images/men-big.png')
        # pixmap.scaled(self.label_image.size(), Qt.KeepAspectRatio)
        # self.label_image.setScaledContents(True)
        self.label_image.setPixmap(pixmap)

        self.label_sn = QLabel("编号: %s" % conf['sn'])
        self.label_name = QLabel("名称: %s" % conf['name'])
        self.label_position = QLabel("位置: %s" % conf['position'])
        self.label_model= QLabel("型号: %s" % conf['model'])

        self.vlayout_info = QVBoxLayout()
        self.vlayout_info.addWidget(self.label_name)
        self.vlayout_info.addWidget(self.label_position)
        self.vlayout_info.addWidget(self.label_model)
        self.vlayout_info.addWidget(self.label_sn)

        # 设备状态 -> 在线状态
        self.online_button = None
        self.online_button = QPushButton('离线')
        self.online_button.setIcon(QIcon(':icons/images/circle-red'))
        self.online_button.setStyleSheet("background-color: rgb(255, 255, 255);")
        self.online_button.setStyleSheet("border:none")
        self.online_button.setFlat(True)

        self.door_button = QPushButton('开启')
        self.door_button.setIcon(QIcon(':icons/images/men-red'))
        self.door_button.setStyleSheet("background-color: rgb(255, 255, 255);")
        self.door_button.setStyleSheet("border:none")
        self.door_button.setFlat(True)

        self.vlayout_status = QVBoxLayout()
        self.vlayout_status.addWidget(self.online_button)
        self.vlayout_status.addWidget(self.door_button)

        self.gridLayout = QGridLayout()
        self.gridLayout.addWidget(self.label_image, 0,0,1,1)
        self.gridLayout.addLayout(self.vlayout_info, 0,1,1,1)
        self.gridLayout.addLayout(self.vlayout_status, 0,2,1,1)
        # self.gridLayout.addWidget(self.online_button, 1,0,1,1)
        # self.gridLayout.addWidget(self.door_button, 2,0,1,1)

        self.setLayout(self.gridLayout)

    def guidaoInit(self, conf):
        # 设备图片
        self.label_image = QLabel(self, pixmap=QPixmap(':icons/images/guidao.png'))
        pixmap = QPixmap(':icons/images/guidao-big.png')
        # pixmap.scaled(self.label_image.size(), Qt.KeepAspectRatio)
        # self.label_image.setScaledContents(True)
        self.label_image.setPixmap(pixmap)

        self.label_sn = QLabel("编号: %s" % conf['sn'])
        self.label_name = QLabel("名称: %s" % conf['name'])
        self.label_position = QLabel("位置: %s" % conf['position'])
        self.label_model= QLabel("型号: %s" % conf['model'])

        self.vlayout_info = QVBoxLayout()
        self.vlayout_info.addWidget(self.label_name)
        self.vlayout_info.addWidget(self.label_position)
        self.vlayout_info.addWidget(self.label_model)
        self.vlayout_info.addWidget(self.label_sn)

        # 设备状态 -> 在线状态
        self.online_button = None
        self.online_button = QPushButton('离线')
        self.online_button.setIcon(QIcon(':icons/images/circle-red'))
        self.online_button.setStyleSheet("background-color: rgb(255, 255, 255);")
        # self.online_button.setStyleSheet("text-align:left")
        self.online_button.setStyleSheet("border:none")
        self.online_button.setFlat(True)
        self.vlayout_status = QVBoxLayout()
        self.vlayout_status.addWidget(self.online_button)

        self.axis = conf['axis']
        gridLayout = QGridLayout()
        n = 0
        self.btn_move_dict = {}
        self.btn_stop_dict = {}
        self.doubleBox_current_dict = {}
        self.doubleBox_target_dict = {}
        for key in self.axis.keys():
            btn_move = QPushButton('移动')
            btn_stop = QPushButton('停止')
            doubleBox_current = QDoubleSpinBox()
            doubleBox_current.setRange(-1000000, 1000000)
            # doubleBox_current.setMinimumSize(size)
            # doubleBox_current.setFont(font)
            doubleBox_current.setDecimals(3)
            doubleBox_current.setEnabled(False)
            doubleBox_target = QDoubleSpinBox()
            doubleBox_target.setRange(-1000000, 1000000)
            # doubleBox_target.setMinimumSize(size)
            # doubleBox_target.setFont(font)
            doubleBox_target.setDecimals(3)
            gridLayout.addWidget(QLabel(self.axis[key]['name']+':'), n,0,1,1)
            gridLayout.addWidget(doubleBox_current, n,1,1,1)
            gridLayout.addWidget(QLabel('->'), n,2,1,1)
            gridLayout.addWidget(doubleBox_target, n,3,1,1)
            gridLayout.addWidget(btn_move, n,4,1,1)
            gridLayout.addWidget(btn_stop, n,5,1,1)
            n += 1
            btn_move.clicked.connect(self.btnMoveClicked)
            btn_stop.clicked.connect(self.btnStopClicked)
            self.btn_move_dict[key] = btn_move
            self.btn_stop_dict[key] = btn_stop
            self.doubleBox_current_dict[key] = doubleBox_current
            self.doubleBox_target_dict[key] = doubleBox_target

        self.gridLayout = QGridLayout()
        self.gridLayout.addWidget(self.label_image, 0,0,1,1)
        self.gridLayout.addLayout(self.vlayout_info, 0,1,1,1)
        self.gridLayout.addLayout(self.vlayout_status, 0,2,1,1)
        # self.gridLayout.addWidget(self.online_button, 1,0,1,1)
        self.gridLayout.addLayout(gridLayout, 0,3,1,1)

        self.setLayout(self.gridLayout)

    def btnMoveClicked(self):
        obj = self.sender()  # 获取发射信号的对象
        for k in self.btn_move_dict:
            if self.btn_move_dict[k] == obj:
                print(self.axis[k])
                break

    def btnStopClicked(self):
        obj = self.sender()  # 获取发射信号的对象
        for k in self.btn_stop_dict:
            if self.btn_stop_dict[k] == obj:
                print(self.axis[k])
                break

    def onlineStatusChange(self, online):
        if online == 1:
            self.online_button.setIcon(QIcon(':icons/images/circle-green'))
            self.online_button.setText('在线')
        if online == 0:
            self.online_button.setIcon(QIcon(':icons/images/circle-red'))
            self.online_button.setText('离线')
            
    def hongwaiStatusChange(self, people):
        if people == 1:
            self.people_button.setIcon(QIcon(':icons/images/people-green'))
            self.people_button.setText('有人')
        if people == 0:
            self.people_button.setIcon(QIcon(':icons/images/people-red'))
            self.people_button.setText('无人')

    def menStatusChange(self, status):
        if status == 1:
            self.door_button.setIcon(QIcon(':icons/images/men-green'))
            self.door_button.setText('开启')
        if status == 0:
            self.door_button.setIcon(QIcon(':icons/images/men-red'))
            self.door_button.setText('关闭')

class DeviceWidget(QWidget, Ui_Form):

    devices = []
    device_cmd = {}

    def __init__(self, parent = None):
        super(QWidget, self).__init__(parent)
        self.setupUi(self)
        # 界面初始化
        self.uiInit()
        # 信号初始化
        self.signalInit()
        # 加载设备
        self.deviceLoadAll()
        # 读取设备控制命令
        self.deviceCmdRead()

    def uiInit(self):
        """ui初始化"""
        # 设备操作
        self.device_service = DeviceServiceJson()
        # mqtt
        self.mqtt = MqttThread()
        # 图标
        self.connect_icon = qta.icon('fa5s.circle', color='springgreen')
        self.disconnect_icon = qta.icon('fa5s.circle', color='red')
        self.pushButton_mqtt_connect.setIcon(self.disconnect_icon)
        # mqtt设置界面
        self.mqttSetDialog = MqttSetDialog()
        # 设备管理界面
        self.deviceManageWidget = DeviceManageWidget()
        # 设备智能
        self.deviceSmartWidget = DeviceSmartWidget()
        # 状态图标
        self.circle_springgreen_icon = qta.icon('fa5s.circle', color='springgreen')
        self.circle_red_icon = qta.icon('fa5s.circle', color='red')

    def signalInit(self):
        """信号初始化"""
        # 设备管理
        self.pushButton_device_manage.clicked.connect(self.deviceManageWidget.show)
        self.pushButton_device_smart.clicked.connect(self.deviceSmartWidget.show)
        # mqtt
        self.pushButton_mqtt_set.clicked.connect(self.mqttSetDialog.show)
        self.pushButton_mqtt_connect.clicked.connect(self.mqttDoConnect)
        self.pushButton_mqtt_disconnect.clicked.connect(self.mqtt.stop)
        self.mqtt.signal_on_message.connect(self.mqttOnMessage)
        self.mqtt.signal_on_connect.connect(self.mqttOnConnect)
        self.mqtt.signal_on_disconnect.connect(self.mqttOnDisconnect)

    def deviceCmdRead(self):
        """读取设备命令"""
        try:
            with open(CONFIG_DEVICE_CMD, 'r', encoding='utf-8') as f:
                self.device_cmd= json.loads(f.read(), object_pairs_hook=OrderedDict)
        except Exception as e:
            logger.info(e)
            QMessageBox.information(self,"提示","读取配置文件失败！", QMessageBox.Yes)
            return False

    def deviceLoadAll(self):
        """加载所有设备"""
        self.devices = self.device_service.getAll()
        self.devices_box_list = []
        n = 0
        for i, element in enumerate(self.devices):
            itemBox = DeviceItemGroupBox(conf=element['value'])
            self.devices_box_list.append(itemBox)
            if element['value']['model'] == 'FSC-05':
                self.gridLayout.addWidget(itemBox, n//3,n%3,1,2)
                n+=1
            else:
                self.gridLayout.addWidget(itemBox, n//3,n%3,1,1)
            n += 1

         
    def mqttDoConnect(self):
        if not self.mqtt.is_connect:
            conf = self.mqttSetDialog.config
            self.mqtt.load_conf(conf)
            self.mqtt.start()
        else:
            QMessageBox.information(self,"提示","已连接服务器！", QMessageBox.Yes)

    def mqttDoDisconnect(self):
        self.mqtt.stop()

    def mqttOnConnect(self):
        self.pushButton_mqtt_connect.setIcon(self.connect_icon)
        logger.info('连接服务器')
        self.mqtt.do_subscribe([(d['value']['pub'], 0) for d in self.devices])
        logger.info('订阅成功')
        # 获取设备是否在线
        for d in self.devices:
            self.mqtt.do_publish(d['value']['pub'], json.dumps(self.device_cmd['get_online']), 0)
            self.mqtt.do_publish(d['value']['pub'], json.dumps(self.device_cmd['infared']['status']), 0)
            self.mqtt.do_publish(d['value']['pub'], json.dumps(self.device_cmd['door']['status']), 0)

    def mqttOnDisconnect(self):
        self.pushButton_mqtt_connect.setIcon(self.disconnect_icon)
        logger.info('连接断开')
        for i, device in enumerate(self.devices):
            self.devices_box_list[i].onlineStatusChange(0)
    
    def mqttOnSubscribe(self):
        logger.info('订阅成功')
    
    def mqttOnMessage(self, topic, message, qos):
        logger.info('收到消息')
        logger.info('topic:%s'%topic)
        logger.info('message:%s'%message)
        logger.info('qos:%s'%qos)
        res = re.match('fsc/(.*?)/([a-zA-Z0-9]{8,16})/tx', topic, re.M|re.I)
        if res == None:
            return
        model = res.group(1)
        sn = res.group(2)
        for i, device in enumerate(self.devices):
            if device['value']['sn'] == sn:
                resp = json.loads(message)
                # 在线状态返回
                if resp['code'] == 100:
                    self.devices_box_list[i].onlineStatusChange(int(resp['msg']))
                    return
                print('查询到设备')
                if model == 'FSC-01': # 光机
                    pass
                if model == "FSC-02": # 门禁
                    if resp['code'] == 120:
                        print('门禁状态')
                        self.devices_box_list[i].menStatusChange(int(resp['msg']))
                    pass
                if model == "FSC-03": # 红外
                    if resp['code'] == 110:
                        print('红外状态')
                        self.devices_box_list[i].hongwaiStatusChange(int(resp['msg']))
                    pass
                if model == "FSC-04": # 辐射源
                    pass
                if model == "FSC-05": # 轨道
                    pass
                break



if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    form = MqttTestWidget()
    form.show()
    app.exec_()
